package org.westboy;

import de.felixroske.jfxsupport.AbstractJavaFxApplicationSupport;
import de.felixroske.jfxsupport.GUIState;
import javafx.application.Platform;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.westboy.common.exception.ApplicationException;
import org.westboy.common.util.AppUtil;
import org.westboy.view.IndexView;
import org.westboy.view.LoginView;
import sun.awt.image.FileImageSource;
import sun.awt.image.ToolkitImage;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;

@EnableScheduling
@SpringBootApplication
public class App extends AbstractJavaFxApplicationSupport {

	public static PopupMenu popupMenu = new PopupMenu();

	public static TrayIcon trayIcon = null;

	public static void main(String[] args) {
		try {
			AppUtil.checkRepeatRun();
			launchApp(App.class, LoginView.class,args);
		} catch (ApplicationException e) {
			AppUtil.showErrorAlert(e);
		}
	}

	@Override
	public Collection<Image> loadDefaultIcons() {
		return Arrays.asList(new Image(getClass().getResource("/icons/icon.png").toExternalForm()));
	}

	@Override
	public void beforeInitialView(Stage stage, ConfigurableApplicationContext ctx) {
		MenuItem showItem = new MenuItem("显示");
		showItem.addActionListener(e -> App.removeSystemTrayIconAndShow());
		MenuItem exitItem = new MenuItem("退出");
		exitItem.addActionListener(e -> App.exit());
		App.popupMenu.add(showItem);
		App.popupMenu.add(exitItem);
		try {
			App.trayIcon = new TrayIcon(ImageIO.read(getClass().getResourceAsStream("/icons/icon_16x16.png")), "美嘉优购", App.popupMenu);
		} catch (IOException ex) {
			ex.printStackTrace();
			AppUtil.showErrorAlert(ex);
		}
	}

	public static void  addSystemTrayIconAndHide(){
		try {
			GUIState.getSystemTray().add(trayIcon);
			Platform.setImplicitExit(false);
			App.getStage().hide();
		} catch (AWTException ex) {
			ex.printStackTrace();
			AppUtil.showErrorAlert(ex);
		}

	}

	public static void removeSystemTrayIconAndShow(){
		GUIState.getSystemTray().remove(trayIcon);
		Platform.runLater(()->App.getStage().show());
	}

	public static void exit(){
		Platform.runLater(()->Platform.exit());
		System.exit(0);
	}

}
